import {defineStore} from 'pinia'
import { login } from '@/service/modules/user'
import {oAuthLogout} from '@/utils/auth'
import Cookie from 'js-cookie'

const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    userInfo: null as any,
    /**TODO: 模块化做整合时考虑到的存储变量，用户历史访问页面 */
    groupCenterMenus: [] as any[],
    historyPages: {} as any[],
    /**当前历史记录 */
    currentHisPages: {
      key: '',
      menus: [] as RouteMenuItem[]
    }
  }),
  actions: {
    getToken () {
      return this.token || localStorage.getItem('token') || ''
    },
    hasToken () {
      return this.getToken()
    },
    romoveToken () {
      this.token = ''
      localStorage.setItem('token', '')
      Cookie.remove('netops-token')
    },
    /**
     * 获取用户信息
     */
    async getUserInfo () {
      // const res:any = await getUserInfo()
      const uStr = localStorage.getItem('userInfo') || ''
      this.userInfo = JSON.parse(uStr)
    },
    /**
     * 登录
     */
    async login (data:any) {
      const res = await login(data)
      const userInfo = res.data
      this.token = 'Bearer ' + userInfo.token
      localStorage.setItem('token', this.token)
      Cookie.set('netops-token', this.token)
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
      return 1
    },
    /**
     * 退出登录
     */
    logout () {
      this.romoveToken()
      oAuthLogout()
    }
  },
})

export default useUserStore
